package Sort;

public class MergeSort {
    /**
     * 归并排序(递归)
     */
    public static void mergeSort(int[] arr){
        merge(arr,0,arr.length-1);
    }
    public static void merge(int[] arr,int left,int right){
        if(left>=right){
            return;
        }
        int mid=(left+right)/2;
        merge(arr,left,mid);
        merge(arr,mid+1,right);
        //合并
        megerTogether(arr,left,mid,right);
    }
    public static void megerTogether(int[] arr,int left,int mid,int right){
        int s1=left;
        int e1=mid;
        int s2=mid+1;
        int e2=right;
        int k=0;
        int[] tmp=new int[right-left+1];
        while (s1<=e1&&s2<=e2){
            if (arr[s1]<arr[s2]){
                tmp[k++]=arr[s1++];
            }
            else {
                tmp[k++]=arr[s2++];
            }
        }
        while (s1<=e1){
            tmp[k++]=arr[s1++];
        }
        while (s2<=e2){
            tmp[k++]=arr[s2++];
        }
        for (int i = 0; i <k; i++) {
            arr[i+left]=tmp[i];
        }
    }


    public static void main(String[] args) {
        int[] array={5,1,9,4,3};
        mergeSort(array);
        for (int i = 0; i <array.length; i++) {
            System.out.print(array[i]+" ");
        }
    }
}
